(function( window, undefined ) {

/*if(window.Util){
	alert('Util己经存在请改变量名!');
	return ;
}*/
var Util = window.Util = {};


Util.isIE = (document.all) ? true : false;
Util.isIE6 = false;
if(Util.isIE && navigator.userAgent){
	if(navigator.userAgent.indexOf("MSIE 6") != -1){
		Util.isIE6 = true;
	}
}

Util.type = function(obj){
	var type = toString.call(obj);
	var jsType = null;
	switch (type) {
	case "[object String]":
		jsType = "string";
		break;
	case "[object Number]":
		jsType = "number";
		break;
	case "[object Boolean]":
		jsType = "boolean";
		break;
	case "[object Undefined]":
		jsType = "undefined";
		break;
	case "[object Null]":
		jsType = "null";
		break;
	case "[object Object]":
		jsType = "object";
		break;
	case "[object Array]":
		jsType = "array";
		break;
	case "[object Function]":
		jsType = "function";
		break;
	case "[object Date]":
		jsType = "date";
		break;
	case "[object RegExp]":
		jsType = "regExp";
		break;
	default:
		jsType = "object";
		break;
	}
	return jsType;
};

Util.isBaseDataType =  function(obj){
	var checkResult = false;
	var type = Util.type(obj);
	if(type == 'string' || type == 'number' || type == 'boolean' || type == 'undefined' || type == 'null' 
		|| type == 'date'){
		checkResult = true; 
	}else{
		checkResult = false;
	}
	return checkResult;
};

Util.el = function(id, property, index){
	if(id && "string" == Util.type(id)){
		var elements ;
		if(property){
			if('id' == property){
				return document.getElementById(id);
			}
			if('name' == property){
				elements = document.getElementsByName(id);
			}
			if('tagName' == property){
				elements = document.getElementsByTagName(id);
			}
			if(index != undefined){
				if("number" == Util.type(index) && index == parseInt(index) && index > -1){
					return elements[index];
				}else{
					throw Error("index invalid dataType, please get it >=0 int number !");
				}
			}else{
				return elements;
			}
		}
		return document.getElementById(id);
	}
	return id;
};



Util.getStyle = function(element, property, index){
	element = Util.el(element, property, index);
	return element.currentStyle || document.defaultView.getComputedStyle(element, null) ;
};

Util.copyProperties = function(dest, src){
	for (var property in src) {
		if(dest[property] == undefined){
			dest[property] = src[property];
		}else{
			var popertyType = Util.type(src[property]);
			if(popertyType == "object" && undefined == src[property].parentNode){//是對象類型,且不為dom
				Util.copyProperties(dest[property], src[property]);
			}else if(popertyType == "array" && dest[property].length != 0){//當對象為數組類型,且目標節點length不為0
				for(var i=0; i < src[property].length; i++){
					var subPopertyType = Util.type(src[property][i]);
					if(subPopertyType == "object" || subPopertyType == "array"){//當為對象功數組類型時
						if(dest[property][i] == null){//當目標數組節點不存在
							dest[property][i] = src[property][i];
						}else{
							Util.copyProperties(dest[property][i], src[property][i]);
						}
					}else{
						dest[property][i] = src[property][i];
					}
				}
			}else{
				dest[property] = src[property];
			}
		}
	}
};

Util.clone = function(obj){
	var newObj ;
	var type = Util.type(obj);
	if(type == "object"){
		newObj = {};
		Util.copyProperties(newObj, obj)
	}else if(type == "array"){
		newObj = [];
		for(var i=0; i<obj.length; i++){
			newObj[i] = Util.clone(obj[i]);
		}
	}else{
		newObj = obj;
	}
	return newObj;
};

Util.Class = {
	create: function() {
		return function() { this.initialize.apply(this, arguments); };//注這arguments取得到方法體上所有的參數組
	}
};

Util.bind = function(object, fun) {
	return function() {//返回一個function:(function在這并沒有被執行),在被call時才執行,fun是外面傳入的function
		return fun.apply(object, arguments) ;
	};
};

Util.bindAsEventListener = function(object, fun) {
	var args = Array.prototype.slice.call(arguments).slice(2) ; //arguments轉為數組然后取索引index為2后面的
	return function(event) {
		return fun.apply(object, [event || window.event].concat(args)) ;
	};
};

Util.addEventHandler = function(element, eventName, fn) {
	if (element.addEventListener) {//ff..w3c
		element.addEventListener(eventName, fn, false);//false表示不立即執行
	} else if (element.attachEvent) {//ie
		element.attachEvent("on" + eventName, fn);
	} else {//共有直接給屬性值
		element["on" + eventName] = fn;
	}
};
Util.removeEventHandler = function(element, eventName, fn) {
	if (element.removeEventListener) {
		element.removeEventListener(eventName, fn, false);
	} else if (element.detachEvent) {
		element.detachEvent("on" + eventName, fn);
	} else { 
		element["on" + eventName] = null;
	}
};




Util.clearAllEmpty = function(str){
	var rstr = "";
	for(var i=0; i < str.length; i++ ){
		if( str.charAt(i) != " " )
	if( escape(str.charAt(i)) != "%0D" )
		if( escape(str.charAt(i)) != "%0A" )
			rstr = rstr + str.charAt(i);
	}
	return rstr;
};


Util.codeLenth = function(str){
	var len = 0;
	for(var i=0; i<str.length; i++){
		if((escape(str.charAt(i))).indexOf("%u")!=-1){
			len++;len++;
		}else{
			len++;
		}
	}
	return(len);
};


Util.checkPwdStr = function(str){
	var numStr = "0123456789";
	var letterStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	var numFlag = false;
	var letterFlag = false;
	//var symbolFlag = false;
	for(var i=0;i<str.length;i++){
		if(numStr.indexOf(str.charAt(i))!=-1){
			numFlag = true;
		}else if(letterStr.indexOf(str.charAt(i))!=-1){
	  		letterFlag = true;
		}
	}
	return (numFlag && letterFlag);
};


Util.checkKey = function(str, keyNum) {
	if(keyNum < 2){
		return true;
	}
	var charString = ["asdfghjkl", "ASDFGHJKL", "lkjhgfdsa", "LKJHGFDSA",
			"zxcvbnm", "ZXCVBNM", "mnbvcxz", "MNBVCXZ", "qwertyuiop", "QWERTYUIOP",
			"poiuytrewq", "POIUYTREWQ", "1234567890", "0987654321"];
	for (var i = 0; i < str.length; i++) {
		for (var j=0; j<charString.length; j++) {
			var charStr = charString[j];
			var index = charStr.indexOf(str.charAt(i));
			if (index == -1)
				continue;
			var charSubs = "";
			var paramSubs = "";
			if (index + keyNum <= charStr.length) {
				charSubs = charStr.substring(index, index + keyNum);
			}
			if (i + keyNum <= str.length) {
				paramSubs = str.substring(i, i + keyNum);//得到傳入時來的字串中的子串(包含str.charAt(i))
			}
			if (charSubs == paramSubs && charSubs != "" && paramSubs != "") {
				return true;
			}
		}
	}
	return false;
};


Util.checkSeq = function(str, seqNum) {
	if(seqNum < 2){
		return true;
	}
	var i, m = 0, n = 0, tmp = 0;// 用來記錄序列數順序的個數
	for (var j=0; j<str.length; j++) {
		i = str.charCodeAt(j);//得到字串中字符的unicode編碼值(包含了ASCII)
		if (i - tmp == 1) {
			m++;
		} else if (i - tmp != 1) {// tmp存放上一個字符,當前字符比上一個字符大1時
			m = 0;
		}

		if (i - tmp == -1) {// 當前字符比上一個字符小1時
			n++;
		} else if (i - tmp != -1) {
			n = 0;
		}

		if (m + 2 > seqNum || n + 2 > seqNum) {// 當m=3時當前字符為第四個字符,因是大于,所以要進行+2處理
			return true;
		}
		tmp = i;
	}
	return false;
};


Util.clearNull = function(obj){
	if(obj != null){
		var type = Util.type(obj);
		if(type == 'array'){
		   for(var i=0; i<obj.length; i++){
			   obj[i] =  clearNull(obj[i]);
		   }
		}
		if(type == 'object'){
			for(var key in obj){
				obj[key] = Util.clearNull(obj[key]);
			}
		}
		return obj;
	}else{
		return "";
	}
};

Util.resetNull = function(obj){
	if(obj != null){
		var type = Util.type(obj);
		if(type == 'array'){
		   for(var i=0; i<obj.length; i++){
			   obj[i] =  resetNull(obj[i]);
		   }
		}
		if(type == 'object'){
			for(var key in obj){
				if(Util.type(obj[key]) == 'object' || Util.type(obj[key]) == 'array'){
					Util.resetNull(obj[key])
				}else if(key.indexOf('.') != -1 && data[key] == null){
					delete obj[key];
				}
			}
		}
	}
};



Util.wordLimit = function(str, limitSize){
	if(str == null)
		return "";
	if(str.length > limitSize){
		str = str.substr(0, limitSize)+"...";
	}
	return str;
};


Util.stripHtml = function(clobStr){
	var str = clobStr.replace(/\r/g,"");
	str = str.replace(/\n/g,"");
	str = str.replace(/\t/g,"");

	str = str.replace("<script[^>]*?>[\s\S]*?<\/script>","");    
	str = str.replace("<style[^>]*?>[\s\S]*?<\/style>","");

	str = str.replace(/<\/?[^>]*>/g, "");	
	str = str.replace(/\s*/g, "");	

	str = str.replace(/&lt;/g,"<");
	str = str.replace(/&gt;/g,">");
	str = str.replace(/&amp;/g,"&");

	str = str.replace(/-->/g,"");
	str = str.replace(/<!--.*/g,"");

	str = str.replace(/&ldquo;/g,"\"");  
	str = str.replace(/&rdquo;/g,"\"");	
	return str.replace(/&nbsp;/g, "");
};




Util.isEmpty = function(obj){
	var type = Util.type(obj);
	var isEmpty = false;
	if(obj == null || obj == undefined || (type == 'string' && obj.trim() == "")){
		isEmpty = true;
	}
	if(type == 'array' && obj.length == 0){
		isEmpty = true;
	}
	if(type == 'object'){
		for ( var name in obj ) {
			return false;
		}
		return true;
	}
	return isEmpty;
};



//window.param = {};
Util.getParam = function(url){
	if(Util.isEmpty(url)){
		url = window.location.href;
	}
	var index = url.indexOf('?');
	if(index == -1){
		return {};
	}
	var queryStr = url.substring(index+1);
	var params = queryStr.split('&');
	var param = {};
	for(var i=0; i<params.length; i++){
		var paramArray = params[i].split('=');
		if(paramArray.length == 2){//当有参数值
			if(param[paramArray[0]] == undefined){//之前没有放入
				param[paramArray[0]] = paramArray[1];//直接放入值
			}else{//之前己放入的
				var arr1;
				if(Util.type(param[paramArray[0]]) == "array"){//当之前己放入的是数组
					arr1 = param[paramArray[0]];
				}else{//当之前己放入的是字串
					arr1 = [];
					param[paramArray[0]] = arr1;
				}
				arr1.push(paramArray[1]);//放入参数值,现在己是数组,所以用push
			}
		}else{
			if(param[paramArray[0]] == undefined){
				param[paramArray[0]] = "";
			}else{
				var arr1;
				if(Util.type(param[paramArray[0]]) == "array"){
					arr1 = param[paramArray[0]];
				}else{
					arr1 = [];
					param[paramArray[0]] = arr1;
				}
				arr1.push("");
			}
		}
	}
	return param;
};

Util.loadJs = function(url, fn){
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.language = 'javascript';
	script.src = url;
	document.getElementsByTagName("head")[0].appendChild(script);
	if(fn){		
		fn();
	}
};
Util.load = function(selector, url){
	//Util.copyProperties(window.param, Util.getParam(url));
	$(selector).load(url);
};

Util.changeUrl = function(param){
	var url = "";
	//提取出参数变成字串
	var data = {//当用户点击后退时触发window.onpopstate时会提供此对象
		title	: "test",
		url		: 'http://localhost:81/com/test/noFreshChangeUrl.html1',
		otherkey: 'ccc'
	};
	window.history.pushState(data, '现在是新的title,当然可以以用原来的(document.title),但现有的浏览器都忽略了', 
			'http://localhost:81/com/test/noFreshChangeUrl.html1');
	//注意在http://必要有,我测的是firefox
	
	//window.history.replaceState(data, title, url);
	document.title = "现在是新的title";//改变title
};

Util.getDataIndex = function(data){
	var dataIndex = {};
	if(!Util.isEmpty(data)){
		for(var i=0; i<data.length; i++){
			dataIndex[data[i].uuid] = i;
		}
	}
	return dataIndex;
};

Util.getIndexs = function(dataIndex, ids){
	var indexs = [];
	for(var i=0; i<ids.length; i++){
		indexs.push(dataIndex[ids[i]]);
	}
	return indexs;
};


/**
 * 正整数>0
 */
Util.isPInt = function(str) {
    var g = /^[1-9]*[1-9][0-9]*$/;
    return g.test(str);
};
/**
 * 正整数(含0)
 */
Util.isPInt1 = function(str) {
	if(Util.isPInt(str) || str == '0')
    	return true;
	return false;
};
/**
 * 大于0的正数(包含0，小数)
 */
Util.isPluses = function(str) {
	var g = /^\d+(?=\.{0,1}\d+$|$)/;
    return g.test(str);
};

Util.checkUnique = function(data, id){
	
};

Util.findDataById = function(data, id){
	for(var i=0; i<data.length; i++){
		if(data[i].id == id){
			return true;
		}
	}
	return false;
};

Util.findDataByUuid = function(data, uuid){
	for(var i=0; i<data.length; i++){
		if(data[i].uuid == uuid){
			return true;
		}
	}
	return false;
};

var key = ['isAdd', 'isUpdate', 'isDelete', 'isDel', 'uuid', '$$hashKey', 'isShowEdit'];
var operateMenu = ["查询", "新增", "修改", "删除"];
Util.removeKey = function(obj){
	var type = Util.type(obj);
	if(Util.isEmpty(obj)){
		return;
	}
	if(type == 'array'){
		for(var i=0; i<obj.length; i++){
			var type1 = Util.type(obj[i]);
			if(type1 == 'object'){
				for(var j=0; j<key.length; j++){
					delete obj[i][key[j]];
				}
			}else if(type1 == 'array'){
				Util.removeKey(obj[i]);
			}
		}
	}else if(type == 'object'){
		for(var i=0; i<key.length; i++){
			delete obj[key[i]];
		}
		for(var mapKey in obj){
			var type2 = Util.type(obj[mapKey]);
			if(type2 == 'object' || type2 == 'array'){
				Util.removeKey(obj[mapKey]);
			}
		}
	}
};

Util.getUuid = function(){
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	return uuid;
};

Util.addUuid = function(obj){
	var type = Util.type(obj);
	if(type == 'array'){
		for(var i=0; i<obj.length; i++){
			obj[i].uuid = Util.getUuid();
		}
	}
	if(type == 'object'){
		obj.uuid = Util.getUuid();
	}
};

Util.upload = function(options){
	var form;
	if(options.formID == undefined){
		$('.espFileUploadDiv').remove();
		$('<div class="espFileUploadDiv" style="display:none;"><form></form></div>').appendTo("body");
		form=$('form', '.espFileUploadDiv');
	    form.attr('enctype', "multipart/form-data");
		form.attr('encoding', "multipart/form-data");
		form.attr('method', "post");
	}else{
		form = $('#'+options.formID);
		form.attr('enctype',"multipart/form-data");
		form.attr('encoding',"multipart/form-data");
	}
	if(options.fileDiv != undefined && options.formID == undefined){
		if($('input[type="file"]',$(options.fileDiv)).length>0){
			$('input[type="file"]',$(options.fileDiv)).each(function(){
				$(this).appendTo(form);
			});
		}else{
			//檔entype給定后.沒有file 域spring底層會報400 的錯誤.這里給個默認file
			$("<input type='file' name='files' value=''/>").appendTo(form);
		}
	}
	if (options.url){
		form.attr('action', options.url);
	}
	var frameId = 'easyui_frame_' + (new Date().getTime());
	var frame = $('<iframe id='+frameId+' name='+frameId+'></iframe>')
		.attr('src', window.ActiveXObject ? 'javascript:false' : 'about:blank')
		.css({position:'absolute', top:-1000, left:-1000
		});
	var t = form.attr('target'), a = form.attr('action');
	form.attr('target', frameId);

	var paramFields = $();
	try {
		frame.appendTo('body');
		frame.bind('load', backLoad);
		for(var n in options.data){
			var f = $('<input type="hidden" name="' + n + '">').val(options.data[n]).appendTo(form);
			paramFields = paramFields.add(f);
		}
		checkState();
		form[0].submit();
	} finally {
		form.attr('action', a);
		t ? form.attr('target', t) : form.removeAttr('target');
		paramFields.remove();
	}
	function checkState(){
		var f = $('#'+frameId);
		if (!f.length)
			return ;
		try{
			var s = f.contents()[0].readyState;
			if (s && s.toLowerCase() == 'uninitialized'){
				setTimeout(checkState, 100);
			}
		} catch(e){
			backLoad();
		}
	}
	var checkCount = 10;
	function backLoad(){
		var frame = $('#'+frameId);
		if (!frame.length)
			return ;
		frame.unbind();
		var data = '';
		try{
			var body = frame.contents().find('body');
			data = body.html();
			if (data == ''){
				if (--checkCount){
					setTimeout(backLoad, 100);
					return;
				}
			}
			var ta = body.find('>textarea');
			if (ta.length){
				data = ta.val();
			} else {
				var pre = body.find('>pre');
				if (pre.length){
					data = pre.html();
				}
			}
		} catch(e){
		}
		if (options.success){
			if(data!=""){
				var _data=(new Function("return "+data))();
				options.success(_data);
			}
		}
		setTimeout(function(){
			frame.unbind();
			frame.remove();
		}, 100);
	}
};

Util.checkFile = function(target,limitFileSize,limitFileType) {
	var fileSize = 0;
	if ($.browser.msie && !target.files) {
		var filePath = target.value;
		var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
		var file = fileSystem.GetFile(filePath);
		fileSize = file.Size;
	} else {
		fileSize = target.files[0].size;
	}
	var size = fileSize / 1024;
	var lfs = limitFileSize||4096;
	if(size > lfs){
		alert("上傳附件大小超過上限"+lfs);
		target.value = "";
	}
	var value = target.value;
	var fileType = value.substring(value.lastIndexOf(".")+1).toLowerCase();
	if(limitFileType != undefined){
		var types = limitFileType.split(','), mistach = false;
		for(var k=0; k<types.length; k++){
			if(fileType == types[k]){
				mistach=true;
				break;
			}
		}
		if(mistach == false){
			alert("不支持上傳的文件格式！");
			target.value = "";
		}
	}
};

Util.getText = function(str){
	return $('<div>'+str+'</div>').text();
};

Util.trim = function(obj){
	var type = Util.type(obj);
	if(type == 'array'){
		for(var i=0; i<obj.length; i++){
			obj[i] = Util.trim(obj[i]);
		}
		return obj;
	}else if(type == 'object'){
		for(var mapKey in obj){
			obj[mapKey] = Util.trim(obj[mapKey]);
		}
		return obj;
	}else if(!Util.isEmpty(obj) && (type == 'string')){
		return obj.trim();
	}else{
		return obj;
	}
};

Util.toString = function(obj){
	var type = Util.type(obj);
	if(type == 'array'){
		for(var i=0; i<obj.length; i++){
			obj[i] = Util.toString(obj[i]);
		}
		return obj;
	}else if(type == 'object'){
		for(var mapKey in obj){
			obj[mapKey] = Util.toString(obj[mapKey]);
		}
		return obj;
	}else if(!Util.isEmpty(obj) && (type == 'string')){
		return obj.trim();
	}else{
		return obj;
	}
};

Util.utf16to8 = function (str) {
	var out, i, len, c;
	out = "";
	len = str.length;
	for(i = 0; i < len; i++) {
	    c = str.charCodeAt(i);   
	    if ((c >= 0x0001) && (c <= 0x007F)) {
		out += str.charAt(i);
	    } else if (c > 0x07FF) {
		out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
		out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
		out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
	    } else {
		out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
		out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
	    }
	}   
	return out;   
};

Util.selectTr = function(selector){
	console.info(selector);
};

Util.join = function(obj, separator){
	var str = '';
	var type = Util.type(obj);
	if(type == 'array'){
		for(var i=0; i<obj.length; i++){
			if(Util.isBaseDataType(obj[i])){
				str += obj[i];
				if(i != obj.length-1){
					if(separator && separator != ''){
						str += separator;
					}else{
						str += ',';
					}
				}
			}
		}
	}else if(type == 'object'){
		for(var key in obj){
			if(Util.isBaseDataType(obj[key])){
				str += (key+'='+obj[key]);
				if(separator && separator != ''){
					str += separator;
				}else{
					str += ',';
				}
			}
		}
	}else{
		str = obj + separator;
	}
	return str;
};

})(window);